package com.yloveg.controller;
import com.yloveg.base.BaseController;
import com.yloveg.common.DateUtil;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {
	private final Logger logger = Logger.getLogger(this.getClass());
	
	@Value("#{system.linux_url}")
	private String linux_url;
	@Value("#{system.img_path}")
	private String img_path;
	@Value("#{system.layedit_path}")
	private String layedit_path;
	@Value("#{system.linux_layedit}")
	private String linux_layedit;
	/*
     *采用spring提供的上传文件的方法单个上传
     */
	@RequestMapping("springUpload")
	    @ResponseBody
	    public Map<String, Object> springUpload(HttpServletRequest request) throws IllegalStateException, IOException{
		Map<String, Object> map = new HashedMap<String, Object>();
		//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
		                request.getSession().getServletContext());
		//检查form中是否有enctype="multipart/form-data"
		if(multipartResolver.isMultipart(request))
		        {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
			//获取multiRequest 中所有的文件名
			Iterator iter=multiRequest.getFileNames();
			while(iter.hasNext()){
				//一次遍历所有文件
				MultipartFile file=multiRequest.getFile(iter.next().toString());
				if(file!=null){
					String path=null;
					// 保存文件路径
					String showPath=null;
					// 显示文件路径
					String prefix=null;
					// 保存的文件名
					String fileName=file.getOriginalFilename();
					// 文件原名称
					System.out.println("上传的文件原名称:"+fileName);
					String tempPath = DateUtil.endFileDir();
					path = img_path+tempPath;
					prefix=DateUtil.transPath()+fileName.substring(file.getOriginalFilename().lastIndexOf("."));
					//上传
					this.SaveFileFromInputStream(file.getInputStream(), path, prefix);
					map.put("path", linux_url+tempPath+prefix);
				}
			}
		}
		return map;
	}
	
	/*
     *采用spring提供的上传文件富文本框专用
     */
	@RequestMapping("layedit")
	    @ResponseBody
	    public Map<String, Object> layedit(HttpServletRequest request) throws IllegalStateException, IOException{
		Map<String, Object> map = new HashedMap<String, Object>();
		//将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
		                request.getSession().getServletContext());
		//检查form中是否有enctype="multipart/form-data"
		if(multipartResolver.isMultipart(request))
		        {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
			//获取multiRequest 中所有的文件名
			Iterator iter=multiRequest.getFileNames();
			while(iter.hasNext()){
				//一次遍历所有文件
				MultipartFile file=multiRequest.getFile(iter.next().toString());
				if(file!=null){
					String path=null;
					// 保存文件路径
					String showPath=null;
					// 显示文件路径
					String prefix=null;
					// 保存的文件名
					String fileName=file.getOriginalFilename();
					// 文件原名称
					System.out.println("上传的文件原名称:"+fileName);
					String tempPath = DateUtil.endFileDir();
					path = layedit_path+tempPath;
					prefix=DateUtil.transPath()+fileName.substring(file.getOriginalFilename().lastIndexOf("."));
					//上传
					this.SaveFileFromInputStream(file.getInputStream(), path, prefix);
					Map<String, Object> data = new HashedMap<String, Object>();
					map.put("code",0);
					map.put("msg","上传成功！");
					map.put("title",fileName);
					data.put("src", linux_layedit+tempPath+prefix);
					data.put("title",fileName);
					map.put("data",data);
				}
			}
		}
		return map;
	}
	/**保存文件  
     * @param stream  
     * @param path  
     * @param filename  
     * @throws IOException  
     */
	public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException   {
		//设置写权限，windows下不用此语句
		File f=new File(path);
		f.setWritable(true, false);
		f.mkdirs();
		FileOutputStream fs=new FileOutputStream( (path + "/"+ filename).replaceAll( "/", System.getProperty("file.separator")));
		byte[] buffer =new byte[1024*1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread=stream.read(buffer))!=-1)   
		        {
			bytesum+=byteread;
			fs.write(buffer,0,byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}
}